/***************************************************************************
 * Copyright 2012 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the research area ICT-2009.1.3
 * Internet of Things and enterprise environments.
 *
 * Authors:
 *      Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.authorisationService.gui.standalone.util;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT network.txtgroup.com)
 *
 */
public class SimplePasswordGenerator {
    
    private static final char[] ALLOWED_CHARS = new char [] {
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',  
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',  
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '_'};
    
    public static final int MINIMUM_PASSWORD_LENGTH = 5;
    
    private Random randomGenerator;
    private int passwordLength;
    
    public SimplePasswordGenerator (int passwordLength) {
        if (passwordLength < MINIMUM_PASSWORD_LENGTH)
            throw new IllegalArgumentException("The minimum password length is: " + MINIMUM_PASSWORD_LENGTH);
        this.passwordLength = passwordLength;
        //this.randomGenerator = new Random(new Date().getTime());
        try {
			this.randomGenerator = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
    
    public String getNextPassword () {
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < passwordLength; i++)
            password.append(ALLOWED_CHARS[randomGenerator.nextInt(ALLOWED_CHARS.length)]);
        return password.toString();
    }

}
